package com.pomelo.common;

import com.pomelo.config.FileConfig;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class FtpUtil {

    private static final Logger log = LoggerFactory.getLogger(FtpUtil.class);

    /**
     * 获取 ftp 连接
     *
     * @return ftp连接对象
     */
    private static FTPClient getFtp() throws IOException {
        FTPClient client = new FTPClient();
        // 创建ftp连接
        client.connect(FileConfig.getIp(), Integer.parseInt(FileConfig.getPort()));
        client.login(FileConfig.getUser(), FileConfig.getPassword());
        client.setConnectTimeout(50000);
        // 设置中文编码集，防止中文乱码
        client.setControlEncoding("UTF-8");
        if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
            log.info("未连接到FTP，用户名或密码错误。");
            client.disconnect();
        } else {
            log.info("FTP连接成功。");
        }
        return client;
    }

    /**
     * 获取文件夹所有文件信息
     * @param path 文件夹目录
     */
    public static void getFiles(String path) throws IOException {
        FTPClient ftp = getFtp();
        // 跳转到指定目录
        ftp.changeWorkingDirectory(path);
        ftp.enterLocalPassiveMode();
        FTPFile[] files = ftp.listFiles();
        for (FTPFile file : files) {
            System.out.println(file.getName());
        }
    }
}
